package co.bugu.code.analysis;

import cn.idev.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.gitlab4j.api.GitLabApi;
import org.gitlab4j.api.models.Commit;
import org.gitlab4j.api.models.Diff;
import org.gitlab4j.api.models.Project;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
public class GitLabCodeChangeExporter {

    public static void main(String[] args) throws Exception {
        String GITLAB_API_URL = "https://gitlab.lbxdrugs.com"; // GitLab API地址
//        String ACCESS_TOKEN = "glpat-RpVcssru2KxRopZsmR_s"; // todo: 替换为你的GitLab Token
        String ACCESS_TOKEN = "glpat-T2JjcyzfwcYfnjyi8CXK"; // todo: 替换为你的GitLab Token


        GitLabApi gitLabApi = new GitLabApi(GITLAB_API_URL, ACCESS_TOKEN);
//        List<Project> projects = gitLabApi.getProjectApi().getProjects();
//        List<User> users = gitLabApi.getUserApi().getUsers();
//        log.info("users:{}", JSON.toJSONString(users, JSONWriter.Feature.PrettyFormat));

//        Project project = gitLabApi.getProjectApi().getProject(3848);
        Project project = gitLabApi.getProjectApi().getProject(3848, true);
        co.bugu.code.analysis.service.entity.Project pro = new co.bugu.code.analysis.service.entity.Project();
        BeanUtils.copyProperties(project, pro);
        EasyExcel.write("d:/project.xlsx", co.bugu.code.analysis.service.entity.Project.class).sheet().doWrite(List.of(pro));
//        log.info("project: {}", JSON.toJSONString(project, JSONWriter.Feature.PrettyFormat));


//        List<ProtectedBranch> protectedBranches = gitLabApi.getProtectedBranchesApi().getProtectedBranches(3848);
//        log.info("protectedBranches:{}", JSON.toJSONString(protectedBranches, JSONWriter.Feature.PrettyFormat));

//        List<Commit> commits = gitLabApi.getCommitsApi().getCommits(project.getId());
//        List<Commit> commits = gitLabApi.getCommitsApi().getCommits(project.getId(), null, new Date(System.currentTimeMillis() - 365 * 24 * 60 * 60 * 1000), new Date(), null, true, true, true);
//
//        List<User> users = gitLabApi.getUserApi().findUsers("guoqian@lbx.com");
//        log.info("users:{}", JSON.toJSONString(users, JSONWriter.Feature.PrettyFormat));
//        List<User> users1 = gitLabApi.getUserApi().findUsers("00110700@lbxdrugs.com");
//        log.info("users1:{}", JSON.toJSONString(users1, JSONWriter.Feature.PrettyFormat));
//        for (Commit commit : commits) {
//
//            log.info("commit", JSON.toJSONString(commit, JSONWriter.Feature.PrettyFormat));
//            Integer additions = commit.getStats().getAdditions();
//            Integer deletions = commit.getStats().getDeletions();
//            Integer total = commit.getStats().getTotal();
//            log.info("additions:{},deletions:{}, total:{}", additions, deletions, total);
//
//            List<Diff> diffs = gitLabApi.getCommitsApi().getDiff(project.getId(), commit.getId());
//            for (Diff diff : diffs) {
//                log.info("different：{}", JSON.toJSONString(diff));
//            }
//        }

//        exportCodeChangesToExcel(gitLabApi, new Date(System.currentTimeMillis() - 24 * 60 * 1000L * 14), new Date(), "D:\\code-change.xlsx");
    }


    /**
     * 导出指定时间段内所有项目的代码变更情况至 Excel
     *
     * @param gitLabApi      GitLab API 客户端实例
     * @param since          起始时间
     * @param until          结束时间
     * @param outputFilePath 输出 Excel 文件路径
     */
    public static void exportCodeChangesToExcel(
            GitLabApi gitLabApi,
            Date since,
            Date until,
            String outputFilePath
    ) {
        List<CodeChangeRecord> changeRecords = new ArrayList<>();

        try {
            List<Project> projects = gitLabApi.getProjectApi().getProjects();

            for (Project project : projects) {
                if (!project.getName().contains("bi")) {
                    continue;
                }
                List<Commit> commits = gitLabApi.getCommitsApi().getCommits(project.getId(), null, since,until);

                for (Commit commit : commits) {
                    Integer deletions = commit.getStats().getDeletions();
                    Integer additions = commit.getStats().getAdditions();
                    Integer total = commit.getStats().getTotal();

                    List<Diff> diffs = gitLabApi.getCommitsApi().getDiff(project.getId(), commit.getId());
                    for (Diff diff : diffs) {
                        System.out.println(JSON.toJSONString(diff));
                    }

//                    changeRecords.add(new CodeChangeRecord(project.getName(), filePath, additions, deletions));

                }
            }

            // 写入 Excel
            EasyExcel.write(outputFilePath, CodeChangeRecord.class)
                    .head(CodeChangeRecord.class)
                    .sheet("代码变更统计")
                    .doWrite(changeRecords);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
